package yunwo.cn.yzstation.view.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView.ScaleType;



import java.io.File;

import yunwo.cn.yzstation.R;
import yunwo.cn.yzstation.base.MyBaseActivity;
import yunwo.cn.yzstation.config.IntentTag;
import yunwo.cn.yzstation.other.ImageCut;
import yunwo.cn.yzstation.utils.DensityUtil;
import yunwo.cn.yzstation.utils.DrawableUtils;
import yunwo.cn.yzstation.utils.UIUtils;


/**
 * Created by linchubin on 2016/3/15.
 */

public class CutPicActivity extends MyBaseActivity implements View.OnClickListener, OnTouchListener {

    private static final String TAG = "CutPicActivity";
    private ImageCut imageCut;
    private boolean capture = false;
    private String picturePath;
    private static final int CAPTURE_PHOTO = 600;

    private static final int SELECT_PHOTO = 601;
    private Display defaultDisplay;
    private static final int NONE = 0;
    private static final int DRAG = 1;
    private static final int ZOOM = 2;

    private int mode = NONE;
    private float oldDist;
    private Matrix matrix = new Matrix();
    private Matrix savedMatrix = new Matrix();
    private PointF prev = new PointF();
    private PointF mid = new PointF();

    float minScaleR = 0.1f; // 最少缩放比例
    static final float MAX_SCALE = 4f; // 最大缩放比例
    float dist = 1f;
    private int mScreenWidth;
    private int mScreenHeight;
    private float titleBarHeight = 119f;
    private float minDistance = 10f;
    public static final String INTENT_PATH ="INTENT_PATH";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_cut_pic);

        imageCut = (ImageCut) findViewById(R.id.cutPicView);
        findViewById(R.id.confirm).setOnClickListener(this);
        findViewById(R.id.cancel).setOnClickListener(this);
        defaultDisplay = getWindowManager().getDefaultDisplay();
        mScreenWidth = defaultDisplay.getWidth();
        mScreenHeight = defaultDisplay.getHeight();
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            picturePath = extras.getString(IntentTag.CUT_PICTURE_PATH);
            capture = extras.getBoolean(IntentTag.IS_CAPTURE);

            // 设置ScaleType为ScaleType.MATRIX，这一步很重要
            imageCut.setScaleType(ScaleType.MATRIX);
            setInitImage();
            imageCut.setOnTouchListener(this);
        }
    }

    @Override
    protected String settiltile() {
        return null;
    }

    @Override
    protected int getLayoutRsid() {
        return R.layout.activity_cut_pic;
    }

    /**
     * 设置初始image的显示
     *
     */
    private void setInitImage() {
        try {
            Bitmap bitmap = DrawableUtils.compressPic(picturePath, mScreenWidth, mScreenHeight);
            // 滤镜的宽和高
            int redius = ImageCut.mRadius * 2;
            RectF rect = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
            if (rect.width() < redius || rect.height() < redius)
                matrix.setScale(redius / rect.width(), redius / rect.height()); // 对小图放大
            imageCut.setImageBitmap(bitmap);
            // bitmap为空就不调用center函数
            if (bitmap != null) {
                center(bitmap,true, true);
            }
            imageCut.setImageMatrix(matrix);
        } catch (Exception e) {
            // TODO: handle exception
//            UIUtils.showToastSafe(R.string.image_damage);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CAPTURE_PHOTO:
                Log.d(TAG, "new File(picturePath).length():" + new File(picturePath).length());
                if (new File(picturePath).length() > 0) {
                    setInitImage();
                } else {
                    finish();
                }
                break;
            case SELECT_PHOTO:
                if (data != null) {
                    Uri uri = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    setInitImage();
                } else {
                    finish();
                }
                break;

            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 从图库中选择图片
     *
     * @param
     */
    public void selectImage() {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.PICK");
        intent.setType("image/*");
        startActivityForResult(intent, SELECT_PHOTO);
    }

    /**
     * 拍照
     *
     * @param
     */
    private void capturePicture() {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(picturePath)));
        startActivityForResult(intent, CAPTURE_PHOTO);
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.confirm:
                File pictureFile = imageCut.onClip();
                intent = new Intent();
                intent.putExtra(INTENT_PATH,pictureFile.getAbsolutePath());
                setResult(RESULT_OK,intent);
                finish();
                break;
           /* case R.id.leftLL:
                if (capture) {
                    capturePicture();
                } else {
                    selectImage();
                }
                matrix = new Matrix();
                break;*/
            case R.id.cancel:
                intent = new Intent();
                intent.putExtra(INTENT_PATH,picturePath);
                setResult(RESULT_OK,intent);
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d(TAG, "keyCode:" + keyCode);
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (capture) {
                capturePicture();
            } else {
                selectImage();
            }
            matrix = new Matrix();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            // 主点按下
            case MotionEvent.ACTION_DOWN:
                savedMatrix.set(matrix);
                prev.set(event.getX(), event.getY());
                mode = DRAG;
                break;
            // 副点按下
            case MotionEvent.ACTION_POINTER_DOWN:
                dist = spacing(event);
                // 如果连续两点距离大于10，则判定为多点模式
                if (spacing(event) > minDistance) {
                    savedMatrix.set(matrix);
                    midPoint(mid, event);
                    mode = ZOOM;
                }
                break;
            case MotionEvent.ACTION_UP: {
                break;
            }
            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                // savedMatrix.set(matrix);
                break;
            case MotionEvent.ACTION_MOVE:
                if (mode == DRAG) {
                    matrix.set(savedMatrix);
                    matrix.postTranslate(event.getX() - prev.x, event.getY() - prev.y);
                } else if (mode == ZOOM) {
                    float newDist = spacing(event);
                    if (newDist > minDistance) {
                        matrix.set(savedMatrix);
                        float tScale = newDist / dist;
                        matrix.postScale(tScale, tScale, mid.x, mid.y);
                    }
                }
                break;
        }
        imageCut.setImageMatrix(matrix);
        // CheckView();
        imageCut.invalidate();
        return true;
    }

    /**
     * 横向、纵向居中
     */
    protected void center(Bitmap bitmap, boolean horizontal, boolean vertical) {
        Matrix m = new Matrix();
        m.set(matrix);
        RectF rect = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
        m.mapRect(rect);

        float height = rect.height();
        float width = rect.width();

        float deltaX = 0, deltaY = 0;

        if (vertical) {
            // 图片小于屏幕大小，则居中显示。大于屏幕，上方留空则往上移，下方留空则往下移
            int screenHeight = (int) (mScreenHeight - DensityUtil.dip2px(getApplicationContext(),
                    titleBarHeight));
            if (height < screenHeight) {
                deltaY = (screenHeight - height) / 2 - rect.top;
            } else if (rect.top > 0) {
                deltaY = -rect.top;
            } else if (rect.bottom < screenHeight) {
                deltaY = screenHeight - rect.bottom;
            }
        }

        if (horizontal) {
            int screenWidth = mScreenWidth;
            if (width < screenWidth) {
                deltaX = (screenWidth - width) / 2 - rect.left;
            } else if (rect.left > 0) {
                deltaX = -rect.left;
            } else if (rect.right < screenWidth) {
                deltaX = screenWidth - rect.right;
            }
        }
        matrix.postTranslate(deltaX, deltaY);
    }

    /**
     * 两点的距离
     */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        //return FloatMath.sqrt(x * x + y * y);
        return (float) Math.sqrt(x * x + y * y);
    }

    /**
     * 两点的中点
     */
    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }
}

